<script setup>
import {ExclamationCircleOutlined, UserOutlined} from '@ant-design/icons-vue'
import {message, Modal} from 'ant-design-vue'
import {ref} from 'vue'
import {createVNode} from 'vue-demi'
import {isLogin, token, user, userListener} from '~/logic'

const [modal, contextHolder] = Modal.useModal();
const visible = ref(false)
const emit = defineEmits(['login']);
const props = defineProps({
  style: {
    type: Object,
    default: () => ({
      marginLeft: '10px',
      marginRight: '10px',
    }),
  },
  type: {
    type: String,
    default: 'primary',
  }
});
if (!userListener.value) {
  window.addEventListener('SYCM_SHOW_USER', () => {
    calcDataSource();
    visible.value = true;
  });
  userListener.value = true;
}
const loginVisible = ref(false);
const handle = () => {
  if (isLogin({
    emit: () => {
      loginVisible.value = true;
    },
  })) {
    calcDataSource();
    visible.value = true
  }
}
const hidePhoneNumber = (phoneNumber) => {
  if (phoneNumber.length !== 11) {
    return phoneNumber; // 假设手机号为11位，如果不是，则直接返回原始值
  }

  const hiddenDigits = phoneNumber.substr(0, 3) + '****' + phoneNumber.substr(7);
  return hiddenDigits;
}

const logout = () => {
  modal.confirm({
    title: '温馨提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: '您确定要退出登录吗？',
    okText: '确认',
    cancelText: '取消',
    onOk() {
      user.value = undefined
      token.value = ''
      message.success('已退出登录！')
      visible.value = false
    },
  })
}
const activeKey = ref('1');
const columns = [
  {
    dataIndex: 'name',
    title: '工具名称',
  }, {
    dataIndex: 'expireTime',
    title: '到期时间',
    align: 'center',
  },
  {
    dataIndex: 'action',
    title: '操作',
    align: 'center',
  }
]
const dataSource = ref([]);
const calcTime = (code) => {
  const expireTime = user.value?.project ? (user.value?.project[code] ? user.value?.project[code].expire_time : ' - - ') : ' - - ';
  // 判断是否过期
  let isExpire = true;
  if (expireTime !== ' - - ') {
    // 和当前时间对比
    const now = new Date();
    const expire = new Date(expireTime);
    if (expire.getTime() >= now.getTime()) {
      isExpire = false;
    }
  }
  return {
    isExpire,
    expireTime,
  }
}
const calcDataSource = () => {
  dataSource.value = [];
  const expire = calcTime('SYCM_REVERT');
  dataSource.value.push({
    code: 'SYCM_REVERT',
    name: '生意参谋指数还原',
    desc: '（市场/竞争外免费）',
    isFree: false,
    expireTime: expire.expireTime,
    isExpire: expire.isExpire,
    link: 'https://sycm.taobao.com/',
  })
  const wxtExpire = calcTime('WXT_TOOL')
  dataSource.value.push({
    code: 'WXT_TOOL',
    name: '万象台工具',
    desc: '',
    isFree: false,
    expireTime: wxtExpire.expireTime,
    isExpire: wxtExpire.isExpire,
    link: 'https://one.alimama.com',
  })
  dataSource.value.push({
    code: 'TAOBAO_TOOL',
    name: '淘宝详情工具',
    desc: '',
    isFree: true,
    expireTime: wxtExpire.expireTime,
    isExpire: wxtExpire.isExpire,
    link: 'https://www.taobao.com',
  })
}
const toBuy = () => {
  window.open('http://www.xingcha365.com/#/vip');
}
const jump = (link) => {
  window.open(link);
}
</script>

<template>
  <contextHolder/>
  <a-button size="small" :type="type" :style="style" @click="handle">
    <slot>
      <UserOutlined/>
    </slot>
  </a-button>
  <a-modal v-model:visible="visible" title="用户信息" :footer="false" width="720px">
    <a-divider/>
    <a-row>
      <a-tabs size="small" v-model:activeKey="activeKey" tab-position="left" style="width: 100%;" animated>
        <a-tab-pane key="1" tab="淘宝店铺工具">
          <a-table :pagination="false" size="small" :columns="columns" :data-source="dataSource" bordered>
            <template #bodyCell="{record,column}">
              <template v-if="column.dataIndex === 'action'">
                <a-button type="primary" size="small"
                          @click="toBuy"
                          v-if="!record.isFree"
                >
                  {{ record.isExpire ? '立即开通' : '立即续费' }}
                </a-button>
                <a-button size="small" type="default" @click="jump(record.link)" v-else> 去使用</a-button>
              </template>
              <template v-else-if="column.dataIndex==='name'">
                <div>
                  {{ record.name }}
                </div>
                <div v-if="record.desc" style="font-size: 12px;color: #666;">
                  {{ record.desc }}
                </div>
              </template>
              <template v-else-if="column.dataIndex==='expireTime'">
                <div v-if="record.isFree" style="color: #666;">
                  免费
                </div>
                <div v-else-if="record.isExpire" style="color: red;">
                  {{ record.expireTime }}
                </div>
                <div v-else>
                  {{ record.expireTime }}
                </div>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="2" tab="京东店铺工具" disabled="">京东店铺工具</a-tab-pane>
        <a-tab-pane key="3" tab="PDD店铺工具" disabled="">PDD店铺工具</a-tab-pane>
        <a-tab-pane key="4" tab="1688店铺工具" disabled="">1688店铺工具</a-tab-pane>
      </a-tabs>
    </a-row>
    <a-divider/>
    <a-row type="flex">
      <a-col>账号：{{ token ? hidePhoneNumber(typeof user==='undefined'?'':user.user_mobile) : '' }}</a-col>
      <a-col flex="1"/>
      <a-col>
        <a-button type="primary" @click="logout">
          退出登录
        </a-button>
      </a-col>
    </a-row>
  </a-modal>
  <user-login-modal v-model:login-visible="loginVisible" @close="()=>loginVisible=false"/>
</template>

<style scoped>

</style>
